<!--
/**
 * @author xuyh0817
 * @email xuyh0817@foxmail.com
 * @date 2023/4/6 18:16
 * @version 1.0.0
 * @doc todo
 * @website todo
 * @description  移动端
 */
 -->
<template>
  <div class="memo-mobile">
    <div class="mobile-btn">
      <el-tooltip :value="!isEdit" content="编辑" placement="top">
        <el-button type="primary" circle icon="el-icon-edit" @click="isEdit = true"></el-button>
      </el-tooltip>
      <el-tooltip :value="!isEdit" content="导出" placement="left">
        <el-button type="success" circle icon="el-icon-position" style="margin-top: 4px;"
                   @click="handleExport"></el-button>
      </el-tooltip>
    </div>
    <el-drawer
        size="100%"
        :show-close="false"
        :visible.sync="isEdit">
      <div style="text-align: center;font-size: 16px; font-weight: bold;" slot="title">
        <span style="color: #409eff">姜的备忘录</span>
        <br/>
        <span style="font-size: 12px;color: #8c939d">在每段文字后添加$符号,图片在段前</span>
      </div>
      <div class="memo-content">
        <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="content"
            maxlength="9999"
            :autosize="{ minRows: 20 }"
            show-word-limit
        >
        </el-input>
        <div class="memo-content-btn">
          <el-button type="primary" size="small" :disabled="!content" icon="el-icon-circle-check"
                     @click="handleComplete">完成
          </el-button>
          <el-button size="small" icon="el-icon-picture-outline" @click="handleAddPhoto">添加图片</el-button>
          <el-button size="small" :disabled="!content" icon="el-icon-circle-close" @click="isEdit = false">取消
          </el-button>
          <el-button size="small" icon="el-icon-refresh-right" @click="content = undefined">清除</el-button>
        </div>

        <div class="memo-photo-group">
          <div class="memo-photo-item" v-for="(item,index) in photos" :key="item.id">
            <img :src="item.src" class="x-render-image"/>
            <el-input-number step-strictly :min="1" :max="99" v-model="item.sort" placeholder="序号"
                             style="width: 100px"></el-input-number>
            <i class="el-icon-close memo-icon-close" @click="handleRemove(item.id)" :data-index="index + 1"></i>
          </div>
        </div>

      </div>
    </el-drawer>
    <input v-if="fileShow" style="display: none;" name="opsFileChange" type="file" accept="image/jpeg,image/png"
           ref="opsFileChange"
           @change="handleFileChange"></input>
    <MainPane :data="data"></MainPane>
  </div>
</template>

<script>
import MainPane from "../MainPane"
import html2canvas from 'html2canvas'


function parseTime(date = new Date(), format = 'yyyy-MM-dd HH:mm:ss') {
  if (arguments.length === 0 || !date) {
    return ''
  }

  if (typeof (date) !== 'object') {
    date = new Date(date)
  }

  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return format
}

export default {
  name: "Mobile",
  components: {
    MainPane
  },
  data() {
    return {
      photos: [],
      fileShow: false,
      data: {},
      isEdit: false,
      content: undefined
    }
  },
  methods: {
    handleComplete() {
      const {content, photos} = this
      const split =
          content.replaceAll("$$$", "$")
              .replaceAll("$$", "$")
              .replaceAll("\r\n", '')
              .replaceAll("\n", '')
              .split('$')

      const title = {
        id: Date.now(),
        text: split[0]?.trim(),
        style: '',
        fontSize: 26,
        lineHeight: 42
      }
      const arr = []

      for (let i = 1; i < split.length; i++) {
        const random = Math.random() + ''
        const text = split[i]?.trim()
        if (!text) {
          continue
        }
        const find = photos.find(item => item.sort === i)
        if (find) {
          const random = Math.random() + ''
          arr.push({
            id: Date.now() + '-' + random.replaceAll('0.', ''),
            type: 'img',
            src: find.src,
            style: ''
          })
        }
        arr.push({
          id: Date.now() + '-' + random.replaceAll('0.', ''),
          type: 'text',
          text: text,
          style: '',
          fontSize: 17,
          lineHeight: 30
        })
      }

      this.data = {
        title,
        content: arr
      }
      this.isEdit = false
    },
    handleAddPhoto() {
      this.fileShow = true
      const index = setInterval(() => {
        if (this.$refs.opsFileChange) {
          this.$refs.opsFileChange.click()
          clearInterval(index)
        }
      }, 200)
    },
    handleRemove(id) {
      const {photos} = this
      const findIndex = photos.findIndex(item => item.id === id);
      if (findIndex !== -1) {
        photos.splice(findIndex, 1)
      }
    },
    handleFileChange(event) {
      const file = event.target.files[0]
      if (file) {
        this.fileShow = false
        const that = this
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = function (event) {
          const result = event.target.result
          if (result) {
            const random = Math.random() + ''
            that.photos.push({
              id: Date.now() + '-' + random.replaceAll('0.', ''),
              src: result,
              sort: 1
            })
          } else {
            this.$message.error('未选择图片')
          }
        }
      } else {
        this.$message.error('未选择图片')
      }
    },
    handleExport() {
      const phoneContext = document.querySelector('div.x-render-phone-main')
      phoneContext.scrollTop = 0
      html2canvas(phoneContext, {
        background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
        scale: 6, // 处理模糊问题
      }).then((canvas) => {
        this.doGenerateImage(canvas)
      })
    },
    doGenerateImage(canvas) {
      const downloadByBlob = function (blobObj) {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = window.URL.createObjectURL(blobObj)
        link.download = `${parseTime(new Date())}.jpg`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }

      const that = this
      const appWrite = function (canvas) {
        const context = canvas.getContext('2d')
        // 【重要】关闭抗锯齿
        context.mozImageSmoothingEnabled = false
        context.webkitImageSmoothingEnabled = false
        context.msImageSmoothingEnabled = false
        context.imageSmoothingEnabled = false
        const dataUrl = canvas.toDataURL("image/jpeg")

        const bitmap = new plus.nativeObj.Bitmap()
        const filename = `${parseTime(new Date())}.jpg`
        bitmap.loadBase64Data(dataUrl)

        bitmap.save(
            "_doc/" + filename, {
              overwrite: true
            },
            function (i) {
              // 保存到系统相册
              plus.gallery.save(
                  i.target,
                  function (d) {
                    //销毁Bitmap图片
                    bitmap.clear();
                    console.log("保存图片到相册成功");
                    that.$message.success('保存图片到相册成功')
                  },
                  function (e) {
                    console.log("保存保存失败");
                    console.error(e)
                  }
              );
            },
            function () {
              bitmap.clear();
            }
        );
        plus.nativeUI.closeWaiting()
      }

      try {
        appWrite(canvas)
      } catch (e) {
        //第一个参数是回调函数
        canvas.toBlob(
            function (blob) {
              downloadByBlob(blob)

            }, "image/jpeg", 1)
      }
    }
  },
  mounted() {
    this.content = `6月4日处务会$
6月4日，内容如下：$`
    this.isEdit = true
  }
}
</script>

<style scoped>
.memo-mobile {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

.memo-mobile .mobile-btn {
  position: absolute;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  bottom: 30px;
  right: 10px;
}

.memo-mobile .memo-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  padding: 8px;
}

.memo-mobile .memo-content .memo-content-btn {
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  margin: 4px 0;
}

.memo-mobile .memo-content .memo-photo-group {
  width: 100%;
  display: flex;
  flex-flow: column nowrap;
  margin: 4px 0;
}

.memo-mobile .memo-content .memo-photo-group .memo-photo-item {
  width: 100%;
  display: grid;
  grid-template-columns: auto 134px;
  place-items: center;
  grid-column-gap: 4px;
  position: relative;
  box-shadow: 0 0 3px #999,
  0 0 3px #999,
  0 0 3px #999,
  0 0 3px #999,
  0 0 3px #999,
  0 0 3px #999,
  0 0 3px #999;
}

.memo-mobile .memo-content .memo-photo-group .memo-photo-item > .memo-icon-close {
  position: absolute;
  top: 10px;
  right: 40px;
  width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: rgba(255, 68, 68, .75);
  box-shadow: 0 0 3px #999,
  0 0 3px #999;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;

}

.memo-icon-close::after {
  content: attr(data-index);
  width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  box-shadow: 0 0 3px #999,
  0 0 3px #999;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  left: 30px;
  position: absolute;
  user-select: none;
}

.memo-mobile .memo-content .memo-photo-group .memo-photo-item .x-render-image {
  width: calc(100vw - 150px);
  border-radius: 8px;
  align-self: center;
  margin: 8px 0;
}

:deep(.is-circle) {
  margin-left: 0 !important;
}

:deep(.el-drawer__header) {
  margin-bottom: 10px !important;
  padding: 8px 8px 0 !important;
}
</style>
